#include "metaitem.h"
#include "metadata.h"
#include "datasuite.h"
#include "dataroot.h"


#include <QTimer>

MetaItem::MetaItem(MetaData *parent) :
    QObject(parent),
    d(new Data())
{
    QTimer::singleShot(0, this, SLOT(onUpdateParent()));
}

MetaItem::MetaItem(const MetaItem &other) :
    QObject(other.parent()),
    d(other.d)
{
}


QString MetaItem::name() const
{
    return d->name;
}


void MetaItem::setName(const QString &name)
{
    d->name = name;
}

bool MetaItem::editable() const
{
    return d->editable;
}

void MetaItem::setEditable(bool editable)
{
    d->editable = editable;
}

QStringList MetaItem::options() const
{
    return d->options;
}

void MetaItem::setOptions(const QStringList &options)
{
    d->options = options;
}


QString MetaItem::referencePath() const
{
    if (d->referenceObject.isNull())
    {
        return d->referencePath;
    }

    return d->referenceObject->objectPath();
}


void MetaItem::setReferencePath(const QString &optionRef)
{
    d->referencePath = optionRef;

    if (!d->referenceObject.isNull() && d->referencePath == d->referenceObject->objectPath())
    {
        return;
    }

    QTimer::singleShot(0, this, SLOT(onUpdateReference()));

}

DataSuite *MetaItem::referenceObject() const
{
    return d->referenceObject;
}

void MetaItem::setReferenceObject(DataSuite *referenceObject)
{
    d->referenceObject = referenceObject;

    if (d->referenceObject.isNull())
    {
        d->referencePath = "";
    }

    d->referencePath = d->referenceObject->objectPath();
}

MetaData *MetaItem::metaData() const
{
    return qobject_cast<MetaData*>(parent());
}


void MetaItem::onUpdateParent()
{
    MetaData* metaData = qobject_cast<MetaData*>(parent());
    if (!metaData)
    {
        return;
    }

    if (metaData->itemIndex(d->name) >= 0)
    {
        return;
    }

    metaData->addItem(this);
}


void MetaItem::onUpdateReference()
{
    if (!metaData() || !metaData()->suite())
    {
        return;
    }

    const AbstractModelItem* root = metaData()->suite()->root();
    if (!root)
    {
        return;
    }

    DataSuite* suite = root->findChild<DataSuite*>(d->referencePath);
    setReferenceObject(suite);
}


